import random
import re

from flask import current_app, jsonify, make_response, request

from ihome import redis_store, constants
from ihome.libs.yuntongxun import sms
from ihome.models import User
from ihome.utils.captcha.captcha import captcha
from ihome.utils.response_code import RET
from . import api


# GETd 127.0.0.1/api/v1.0/image_codes/<image_code_id>
@api.route("/image_codes/<image_code_id>")
def get_image_code(image_code_id):
    """
    获取图片验证码
    :return:  正常：验证码图片  异常：返回json
    """
    # 业务逻辑处理
    # 生成验证码图片
    name, text, image_data = captcha.generate_captcha()
    # 将验证码真实值与编号保存到redis中
    # redis_store.set("image_code_%s" % image_code_id, text)
    # redis_store.expire("image_code_%s" % image_code_id, )
    try:
        redis_store.setex("image_code_%s" % image_code_id, constants.IMAGE_CODE_REDIS_EXPIRES, text)
    except Exception as e:
        # 记录日志
        current_app.logger.error(e)
        # 返回值
        return jsonify(error=RET.DBERR, errmsg="save image code id failed")
    # 返回图片
    resp = make_response(image_data)
    resp.headers["Content-Type"] = "image/jpg"
    return resp


@api.route('/smscode')
def get_sms_code():
    mobile = request.args.get('mobile')
    imageCode = request.args.get('code')
    imageCodeId = request.args.get('codeId')

    if not all([mobile, imageCode, imageCodeId]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不全")

    if not re.match(r'1[3456789]\d{9}$', mobile):
        return jsonify(errno=RET.PARAMERR, errmsg="手机号码格式有误")

    try:
        if not User.query.filter_by(mobile=mobile):
            return jsonify(errno=RET.PARAMERR, errmsg="该手机号已经被注册")
    except Exception as e:
        current_app.logger.error(e)

    real_imageCode = redis_store.get("image_code_%s" % imageCodeId)

    if not real_imageCode:
        return jsonify(errno=RET.DATAERR, errmsg="获取数据失败")

    try:
        redis_store.delete("image_code_%s" % imageCodeId)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg="删除redis数据失败")

    if not real_imageCode.lower() != imageCode.lower():
        return jsonify(errno=RET.PARAMERR, errmsg="验证码有误")

    sms_code = "%06d" % random.randint(0, 999999)
    print(sms_code)
    try:
        redis_store.setex('SMSCode_' + mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='存储数据异常')

    # 9、调用云通讯发送短信方法
    try:
        ccp = sms.CCP()
        results = ccp.send_template_sms(mobile, [sms_code, constants.SMS_CODE_REDIS_EXPIRES / 60], 1)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg='发送短信异常')

    if results == 0:
        return jsonify(errno=RET.OK, errmsg='发送成功')
    else:
        return jsonify(errno=RET.THIRDERR, errmsg='发送失败')
